import 'dart:io';

import '../../../flutter_base_plugin.dart';

class ErrorHandle {
  // 错误信息
  // ignore: missing_return
  static HttpErrorBean createErrorEntity(error) {
    if (error is DioError) {
      switch (error.type) {
        case DioErrorType.cancel:
          return HttpErrorBean(code: HttpCode.cancel, message: "请求取消");
        case DioErrorType.connectTimeout:
          return HttpErrorBean(code: HttpCode.connectTimeout, message: "连接超时");
        case DioErrorType.sendTimeout:
          return HttpErrorBean(code: HttpCode.sendTimeout, message: "请求超时");
        case DioErrorType.receiveTimeout:
          return HttpErrorBean(code: HttpCode.receiveTimeout, message: "响应超时");
        case DioErrorType.response:
          try {
            int? errCode = error.response?.statusCode;
            String? errMsg = error.response?.data;
            return HttpErrorBean(code: errCode, message: errMsg);
          } on Exception catch (_) {
            return HttpErrorBean(code: HttpCode.unKnowError, message: "未知错误");
          }
        case DioErrorType.other:
          dynamic e = error.error;
          if (e is SocketException) {
            return HttpErrorBean(code: HttpCode.apiConnectionException, message: 'API连接异常，请检查接口！');
          }
          if (e is HttpException) {
            return HttpErrorBean(code: HttpCode.serverException, message: '服务器异常！');
          }
          if (e is FormatException) {
            return HttpErrorBean(
                code: HttpCode.serverException, message: '无效端口！');
          }
          return HttpErrorBean(code: HttpCode.unKnowError, message: "未知错误");
        default:
          return HttpErrorBean(
              code: HttpCode.unKnowError, message: error.message);
      }
    }
    if (error is TypeError) {
      return HttpErrorBean(
          code: HttpCode.unKnowError, message: error.toString());
    }
    return HttpErrorBean(code: HttpCode.unKnowError, message: error.toString());
  }
}
